package com.letv.android.client.episode;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;

import com.letv.android.client.episode.fragment.HalfPlayCommentFragment;
import com.letv.android.client.episode.fragment.HalfPlayRelatedFragment;
import com.letv.android.client.episode.fragment.HalfPlayVideosFragment;

public class DetailPlayFragmentMannager {
	
	private Fragment[] fragments = null;

    private boolean isVideoNormal = false;

    
	public DetailPlayFragmentMannager(FragmentManager fm, boolean isVideoNormal){
	    removeFragments(fm);
	    
        this.isVideoNormal = isVideoNormal;        
        if(isVideoNormal){
            fragments = new Fragment[3] ;
        }else{
            fragments = new Fragment[2] ;
        }
        
	}
	
	public Fragment newInstance(int pageId) {

		if(isVideoNormal){
            switch (pageId) {
                case 0:
                    if(fragments[pageId] == null){
                        fragments[pageId] = new HalfPlayVideosFragment();
                    }

                    return fragments[pageId];
                case 1:
                    if(fragments[pageId] == null){
                        fragments[pageId] = new HalfPlayCommentFragment();
                    }

                    return fragments[pageId];
                case 2:
                    if(fragments[pageId] == null){
                        fragments[pageId] = new HalfPlayRelatedFragment();
                    }

                    return fragments[pageId];
            }
        }else{
            switch (pageId) {
                case 0:
                    if(fragments[pageId] == null){
                        fragments[pageId] = new HalfPlayCommentFragment();
                    }

                    return fragments[pageId];
                case 1:
                    if(fragments[pageId] == null){
                        fragments[pageId] = new HalfPlayRelatedFragment();
                    }

                    return fragments[pageId];
            }
        }
		return null;
	}
	
	private void removeFragments(FragmentManager fm) {
	    if (fragments != null && fragments.length > 0) {
	        for(int i = 0 ; i < fragments.length ; i++){
    			if(fragments[i] != null){
    				/*
    				 * 如果在Activity保存完状态后再给它添加Fragment就会出错。解决办法就是把commit（）方法替换成 commitAllowingStateLoss()就行
    				 */
    				fm.beginTransaction().remove(fragments[i]).commitAllowingStateLoss();
    				fragments[i] = null ;
    			}
    		}
    		fragments = null ;
	    }
	}
}
